import React, {
    Component,
    useState,
    useContext,
    useMemo,
    useEffect,
} from "react";
import {
    HashRouter, // 使用 <HashRouter></HashRouter> 包裹，配置路由,这种方式 路径中有 #
    BrowserRouter, // 使用 <BrowserRouter></BrowserRouter> 包裹，配置路由,这种方式 路径中没有 #
    Routes,
    Route,
    Navigate,
    useNavigate,
    useLocation
} from "react-router-dom";
import {
    ConfigProvider,
    Breadcrumb,
    Layout,
    Menu,
    theme,
    Button,
    Dropdown,
    Space,
    Switch,
    Avatar
} from "antd";
import {
    HomeOutlined,
    SettingFilled,
    UserOutlined,
    MenuUnfoldOutlined,
    MenuFoldOutlined,
    AppleOutlined,
    TranslationOutlined,
    MoonOutlined,
    SunOutlined
} from "@ant-design/icons";


import { Context } from "../contextStore";

import Login from "../views/login/Login";

import Home from "../views/home/Home";
import More from "../views/more/More";
import ImportCss from "../views/testcss/importcss";
import Cssmoudle from "../views/testcss/cssmoudle";
import StyledComponent from "../views/testcss/styledComponent";
import EffectHook from "../views/myhooks/EffectHook";
import ReducerHook from "../views/myhooks/ReducerHook";
import RefHook from "../views/myhooks/RefHook";
import UseMemoHook from "../views/myhooks/UseMemoHook";
import ContextHook from "../views/myhooks/ContextHook";
import Antd1 from "../views/antdTest/Antd1";
import Antd2 from "../views/antdTest/Antd2";
import Antd3 from "../views/antdTest/Antd3";
import Antd4 from "../views/antdTest/Antd4";

import cssObj from "./index.module.css";


import { useTranslation } from "react-i18next";
import Cookies from 'js-cookie'



const { Header, Content, Sider, Footer } = Layout;

const {
    demoLogo,
    leftSide,
    rightSide
} = cssObj;

const iconsMap = new Map([
    ["home", HomeOutlined],
    ["setting", SettingFilled],
    ["user", UserOutlined],
    ["apple", AppleOutlined],
]);

const createIconEle = (iconName) => {
    const iconEle = iconsMap.get(iconName);
    return React.createElement(iconEle);
};

const LayoutEle = (props) => {
    const [contextState, contextDispatch] = useContext(Context);
    const { menuData } = contextState;
    const [collapsed, setCollapsed] = useState(false);
    const [curMenuKey, setCurMenuKey] = useState("1");
    const [onlyFirstLevel, setOnlyFirstLevel] = useState(true); // 是否只有一级菜单
    const navigate = useNavigate();
    const location = useLocation();

    const {i18n,t} = useTranslation(); // 国际化
    // 切换语言
    const handleLanguage = (lang) => {
        if (lang === i18n.language) return;
        localStorage.setItem("lang", lang);
        window.location.reload();
        // i18n.changeLanguage(lang);
    }
    // const items = [
    //     {
    //         key: 'zh',
    //         label: (
    //             <a onClick={() => {handleLanguage('zh')}}>中文</a>
    //         ),
    //     },
    //     {
    //         key: 'en',
    //         label: (
    //             <a onClick={() => {handleLanguage('en')}}>English</a>
    //         ),
    //     },
    // ];

    const handleMode = (val) => {
        // 此处需要将设置主题的事件传给父组件，父组件设置主题
        const curTheme = val ? "dark" : "light";
        props.setTheme(curTheme);
    }

    const handleSelectMenu = ({ item, key, keyPath, selectedKeys, domEvent }) => {
        console.log(key, "menuKey");
        setCurMenuKey(key);
        setNavSelectedKeys(selectedKeys);
        // 根据key确定当前节点
        const curNode = menuData.find((item) => item.id === Number(key));
        // 路由跳转
        // 先处理只有一级的菜单
        if (!curNode.children || !curNode.children.length) {
            setOnlyFirstLevel(true);
            const curNav = menuData.find((item) => item.id === Number(key));
            const curNavPath = curNav?.path;
            navigate(curNavPath);
            setSubSelectedKeys([]);
        } else {
            // 处理有二级菜单的
            // 找到当前选择的一级菜单下的子菜单的第一个叶子节点
            setOnlyFirstLevel(false);
            const firstLeafMenu = findFirstLeaf(
                menuData.find((item) => item.id === Number(key)).children
            );
            const firstLeafMenuPath = firstLeafMenu.path;
            navigate(firstLeafMenuPath);
            setSubSelectedKeys([firstLeafMenu.id.toString()]);
        }
    };
    // 写一个方法，递归找到一个树形结构中的第一个叶子节点
    const findFirstLeaf = (menu) => {
        for (let i = 0; i < menu.length; i++) {
            if (!menu[i].children?.length) {
                return menu[i];
            } else {
                const res = findFirstLeaf(menu[i].children);
                if (res) {
                    return res;
                }
            }
        }
    };
    const [navSelectedKeys, setNavSelectedKeys] = useState(["1"]);
    const [subSelectedKeys, setSubSelectedKeys] = useState([]);
    const [curYear, setCurYear] = useState(new Date().getFullYear());

    const navs = menuData.map((item) => ({
        key: item.id,
        // label: item.name,
        label: t(item.key),
    }));
    const subNavs = useMemo(() => {
        const curMenu = menuData.find((item) => item.id === Number(curMenuKey));
        const curMenuChildren = curMenu?.children || [];
        if (curMenuChildren?.length) {
            const navList = curMenuChildren.map((item) => {
                const obj = {
                    key: item.id,
                    // label: item.name,
                    label: t(item.key),
                    icon: createIconEle(item.icon),
                };
                if (item.children?.length) {
                    obj.children = item.children.map((ele) => {
                        return {
                            key: ele.id,
                            // label: ele.name,
                            label: t(ele.key),
                        };
                    });
                }
                return obj;
            });
            return navList;
        }
        return [];
    }, [curMenuKey]);

    const {
        token:
            {
                colorBgBase, // 基础背景色
                colorBgContainer, // 容器背景色
                colorTextBase, // 基础文字颜色
                borderRadiusLG, // 大圆角
            },
    } = theme.useToken();

    const selectSub = ({ item, key, keyPath, selectedKeys, domEvent }) => {
        console.log(key, "subKey", typeof key);
        console.log(keyPath, "keyPath");
        // 通过key获取当前选中的二级菜单或三级菜单的path
        setSubSelectedKeys([key]);
        const curMenu = menuData.find((item) => item.id === Number(curMenuKey));
        const curMenuChildren = curMenu?.children || [];
        const curSub = findNode(curMenuChildren, "id", Number(key));
        const curSubPath = curSub?.path;
        if (curSubPath) {
            navigate(curSubPath);
        }
    };

    const getNamesFromRootToPath = (menuData, path) => {
        console.log(path, "传入的path");
        let navNode = menuData.find((item) => item.path === path);
        if (navNode) {
            // 说明是一级
            console.log("一级满足");
            return [navNode.key];
        } else {
            // 二级以上
            let names = [];
            // 先将当前节点通过path找到
            let curNode = findNode(menuData, "path", path);
            if (curNode) {
                // 将当前节点名称添加到names中
                names.push(curNode.key);
                // 每个节点都有一个parentId,通过parentId找到父节点,将父节点名称添加到names中，位置在上一个的前面
                while (curNode.parentId) {
                    curNode = findNode(menuData, "id", curNode.parentId);
                    if (curNode) {
                        names.unshift(curNode.key);
                    }
                }
            }

            return names;
        }
    };
    const findNode = (menuD, keyType, key) => {
        for (let i = 0; i < menuD.length; i++) {
            if (menuD[i][keyType] === key) {
                return menuD[i];
            } else if (menuD[i].children?.length) {
                const res = findNode(menuD[i].children, keyType, key);
                if (res) {
                    return res;
                }
            }
        }
    };

    // 当前路由路径变化时，获得面包屑导航
    const breadcrumbs = useMemo(() => {
        const names = getNamesFromRootToPath(menuData, location.pathname);
        const items = names.map((item, index) => {
            return {
                key: index,
                // title: item,
                title: t(item)
            };
        });
        return items;
    }, [location.pathname]);

    // 当前路由路径变化时,设置当前的nav和subNav
    useEffect(() => {
        // 根据当前路径找到当前的节点
        let curNode = findNode(menuData, "path", location.pathname);
        if (curNode) {
            let rootNode = JSON.parse(JSON.stringify(curNode));
            // 找到当前的路径的根节点
            while (rootNode.parentId) {
                rootNode = findNode(menuData, "id", rootNode.parentId);
            }
            console.log(rootNode, "根节点");
            // 设置当前的nav的key和selectedKeys
            setCurMenuKey(String(rootNode.id));
            setNavSelectedKeys([String(rootNode.id)]);
            // 设置当前的subNav的subSelectedKeys
            // 先处理只有一级的菜单的情况
            if (!rootNode.children || !rootNode.children.length) {
                setSubSelectedKeys([]);
                setOnlyFirstLevel(true);
            } else {
                // 处理有二级菜单的情况
                setSubSelectedKeys([curNode.id.toString()]);
                setOnlyFirstLevel(false);
            }
        }
    }, [location.pathname]);

    const translateDropdownRender = () => {
        return (
            <Menu
                items={[
                    {
                        key: 'zh',
                        label: (
                            <a onClick={() => {handleLanguage('zh')}}>中文</a>
                        ),
                    },
                    {
                        key: 'en',
                        label: (
                            <a onClick={() => {handleLanguage('en')}}>English</a>
                        ),
                    },
                ]}
            />
        );
    }

    const handleExit = () => {
        Cookies.remove("token");
        window.location.replace('/login');
    }

    const avatarDropdownRender = () => {
        return (
            <Menu
                items={[
                    {
                        key: "personalcenter",
                        label: (
                            <a onClick={() => {navigate('/more/personal')}}>个人中心</a>
                        ),
                    },
                    {
                        key: "exit",
                        label: (
                            <a onClick={handleExit}>退出登录</a>
                        ),
                    },
                ]}
            />
        );
    }

    return (
        <Layout>
            <Header
                style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    background: colorBgBase, // 设置背景色
                }}
            >
                <div className={leftSide}>
                    <div className={demoLogo}>
                        <img src={"/logo.png"} alt="logo" />
                    </div>
                    {/* 一级菜单 */}
                    <Menu
                        // theme="dark"
                        mode="horizontal"
                        selectedKeys={navSelectedKeys}
                        onSelect={handleSelectMenu}
                        items={navs}
                        style={{
                            // flex: 1,
                            // minWidth: 0,
                            background: colorBgBase, // 设置背景色
                        }}
                    />
                </div>
                <div className={rightSide}>
                    <Dropdown
                        placement="bottomRight"
                        // menu={{
                        //     items,
                        // }}
                        dropdownRender={translateDropdownRender}
                    >
                        <TranslationOutlined
                            style={{
                                fontSize: 20,
                                color: colorTextBase,
                                cursor: 'pointer'
                            }}
                        />
                    </Dropdown>
                    <Switch
                        checkedChildren={<MoonOutlined />}
                        unCheckedChildren={<SunOutlined />}
                        onChange={handleMode}
                        defaultChecked={props.themeMode === 'dark'}
                        style={{
                            marginLeft: '12px'
                        }}
                    />
                    {/* 头像 */}
                    <Dropdown
                        dropdownRender={avatarDropdownRender}
                        trigger={['click']}
                        placement="bottomRight"
                    >
                        <Avatar
                            size={40}
                            src={'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'}
                            alt="avatar"
                            style={{
                                marginLeft: '12px',
                                cursor: 'pointer'
                            }}
                        />
                    </Dropdown>
                    
                </div>
            </Header>
            <Layout
            >
                {onlyFirstLevel ? null : (
                    <Sider
                        trigger={null}
                        collapsible
                        collapsed={collapsed}
                        width={200}
                        style={{
                            background: colorBgContainer,
                        }}
                    >
                        {/* 二三级菜单 */}
                        <Menu
                            mode="inline"
                            selectedKeys={subSelectedKeys}
                            style={{
                                height: "100%",
                                borderRight: 0,
                            }}
                            items={subNavs}
                            onSelect={selectSub}
                        />
                    </Sider>
                )}

                <Layout
                    style={{
                        // padding: "0 24px 24px",
                        padding: "0 24px",
                    }}
                >
                    <div
                        style={{
                            display: "flex",
                            alignItems: "center",
                        }}
                    >
                        {onlyFirstLevel ? null : (
                            <Button
                                type="text"
                                icon={
                                    collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />
                                }
                                onClick={() => setCollapsed(!collapsed)}
                                style={{
                                    fontSize: "16px",
                                    width: 64,
                                }}
                            />
                        )}
                        <Breadcrumb
                            items={breadcrumbs}
                            style={{
                                margin: "16px 0",
                            }}
                        />
                    </div>

                    <Content
                        style={{
                            padding: 24,
                            margin: 0,
                            // minHeight: 280,
                            // maxHeight: 692,
                            // height: 702,
                            height: 'calc(100vh - 120px - 65px)', // 100vh - 头部高度 - 底部高度
                            overflow: 'auto',
                            background: colorBgContainer,
                            borderRadius: borderRadiusLG,
                        }}
                    >
                        {/* 路由组件 */}
                        <Routes>
                            <Route exact={true} path="/home" Component={Home} />
                            <Route exact={true} path="/more" Component={More} />
                            <Route exact={true} path="/study/effectHook" Component={EffectHook} />
                            <Route exact={true} path="/study/reducerHook" Component={ReducerHook} />
                            <Route exact={true} path="/study/refHook" Component={RefHook} />
                            <Route exact={true} path="/study/memoHook" Component={UseMemoHook} />
                            <Route exact={true} path="/study/contextHook" Component={ContextHook} />
                            <Route exact={true} path="/other/style/normal" Component={ImportCss} />
                            <Route exact={true} path="/other/style/module" Component={Cssmoudle} />
                            <Route exact={true} path="/other/style/styledCompnent" Component={StyledComponent} />
                            <Route exact={true} path="/other/antds/antd1" Component={Antd1} />
                            <Route exact={true} path="/other/antds/antd2" Component={Antd2} />
                            <Route exact={true} path="/other/antds/antd3" Component={Antd3} />
                            <Route exact={true} path="/other/antds/antd4" Component={Antd4} />
                            <Route exact={true} path="/more/personal" element={<div>个人中心TODO</div>} />
                            <Route path="/*" element={<Navigate replace to="/home" />} />
                        </Routes>
                    </Content>
                </Layout>
            </Layout>
            <Footer>
                <div style={{ textAlign: "center" }}>iSuke ©{curYear} Created by TakZhang</div>
            </Footer>
        </Layout>
    );
};

const ConfigEle = () => {
    const [themeMode, setThemeMode] = useState(localStorage.getItem("themeMode")); // 主题模式 dark/light
    const handleTheme = (curTheme) => {
        setThemeMode(curTheme);
        // 设置localStorage的主题色
        localStorage.setItem("themeMode", curTheme);
    }
    return (
        <>
            {
                Cookies.get('token') ? (
                    <ConfigProvider
                        theme={{
                            token: {
                                colorPrimary: "#1DA57A", // '#00b96b' '#1890ff', '#1DA57A'
                                borderRadius: 2,
                                borderRadiusLG: 8,

                                // colorBgContainer: '#f6ffed',
                            },
                            algorithm: themeMode === "light" ? theme.defaultAlgorithm : theme.darkAlgorithm,
                            cssVar: true,
                            hashed: false,
                        }}
                    >
                        <HashRouter>
                            <LayoutEle setTheme={(curTheme) => {handleTheme(curTheme)}} themeMode={themeMode} />
                        </HashRouter>
                    </ConfigProvider>
                ) : (
                    <HashRouter>
                        <Routes>
                            <Route exact={true} path="/login" Component={Login} />
                            <Route path="/*" element={<Navigate replace to="/login" />} />
                        </Routes>
                    </HashRouter>
                )
            }
        </>
    )
}
export default ConfigEle;